package cn.com.joycode.nimble.web.spring;

import cn.com.joycode.nimble.core.utils.ObjectMapperUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;

import java.util.List;

public class WebMvcUtils {
    private WebMvcUtils() {

    }

    /**
     * 找到http message converters中的jackson converter
     *
     * @param converters
     * @return
     */
    public static MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> httpMessageConverter : converters) {
            if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {
                return (MappingJackson2HttpMessageConverter) httpMessageConverter;
            }
        }
        return null;
    }

    /**
     * 对jackson http message converter进行统一规格化
     *
     * @param converters
     */
    public static void normalizeMappingJackson2HttpMessageConverter(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = getMappingJackson2HttpMessageConverter(converters);
        ObjectMapper objectMapper;
        if (ObjectUtil.isNull(mappingJackson2HttpMessageConverter)) {
            mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
            objectMapper = ObjectMapperUtil.getObjectMapper();
            mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
            converters.add(mappingJackson2HttpMessageConverter);
        } else {
            objectMapper = mappingJackson2HttpMessageConverter.getObjectMapper();
            ObjectMapperUtil.normalize(objectMapper);
        }
    }

    public static String getBearerAuthorization(ServerHttpRequest request) {
        List<String> headList = request.getHeaders().get("Authorization");
        if (headList.size() == 0) {
            return null;
        }
        String authInfo = headList.get(0);
        return StrUtil.removePrefix(authInfo, "Bearer ");
    }
}
